package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.adapter.ChooseBackCardAdapter;
import com.century.sjt.entity.BankCard;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.window.ChoosePayPopupWindowS;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:周玲波
 * @Description: 提现
 * @date : 2016/8/20 15:37
 */
public class WalletToCosumeActivity extends BaseActivity {
    SjtTitleBar wallet_tocosume_title;
    private Button btn_OK;
    private LinearLayout payTypeLayout, Layout_addBankPay;
    private EditText  edtCosume;
    private EditText edFee;
    private TextView tBankNanme, tBankNumber_Type;
    private ImageView imgBankLogo;
    private String aBankName, aBankNumber, aBankType;

    private ListView listView;
    private final com.century.sjt.entity.BankCard payBack = new BankCard();
    private ChooseBackCardAdapter adapter;
    private List<BankCard> mDatalist = new ArrayList<>();
    private Handler mHandler;

    private ChoosePayPopupWindowS popupWindow;


    private String Bamount = "";//余额
    private String BankCard = "";//银行卡号
    private String Cosume = "";//提现金额
    private String BankCardType = "";//银行卡类型
    private String textFee = "";//手续费

    private LinearLayout layout_account_fee;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_wallet_tocosume);



        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        };

        adapter = new ChooseBackCardAdapter(WalletToCosumeActivity.this, mDatalist, mHandler, "0");//0置灰，1显示信用卡

        initView();
//        getBindBankCard();
        initEvent();

    }


    @Override
    protected void initView() {
        btn_OK = (Button) findViewById(R.id.c_btn_pay);
        wallet_tocosume_title= (SjtTitleBar) findViewById(R.id.wallet_tocosume_title);
        wallet_tocosume_title.setTitle(getResources().getString(R.string.btn_depositor));
        wallet_tocosume_title.setLeftIconResource(getResources().getString(R.string.icon_return));
        wallet_tocosume_title.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edtCosume = (EditText) findViewById(R.id.c_cosume);
        imgBankLogo = (ImageView) findViewById(R.id.c_yh_image);
        edFee = (EditText) findViewById(R.id.et_fee);
        tBankNanme = (TextView) findViewById(R.id.c_bankname);
        layout_account_fee = (LinearLayout) findViewById(R.id.layout_account_fee);
//        tBankNumber_Type=(TextView)findViewById(R.id.c_banknumber_type);
        payTypeLayout = (LinearLayout) findViewById(R.id.c_layout_pay_type);
    }

    @Override
    protected void initEvent() {

        layout_account_fee.setVisibility(View.GONE);
        btn_OK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Cosume = edtCosume.getText().toString();
                if (mDatalist.size() == 0) {
                    TipUtil.showToast(getResources().getString(R.string.error_please_add_bankcard), WalletToCosumeActivity.this, 1);
                } else if (Cosume.equals("") || "0".equals(Cosume)) {
                    TipUtil.showToast(getResources().getString(R.string.error_please_input_cosume_amount), WalletToCosumeActivity.this, 1);
                } else if (BankCardType.equals(getResources().getString(R.string.text_bankcard_type_2))) {
                    TipUtil.showToast(getResources().getString(R.string.error_nonsupport_credit_card), WalletToCosumeActivity.this, 1);
                } else {
                    withdraw(Cosume, BankCard);

                }


            }
        });
        edtCosume.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
//                    if (imm.isActive()) {
//                        imm.hideSoftInputFromWindow(
//                                v.getApplicationWindowToken(), 0);
//                    }

//                    edittext.setText("success");
//                    webview.loadUrl(URL);
                    Cosume = edtCosume.getText().toString();
                    if (mDatalist.size() == 0) {
                        TipUtil.showToast(getResources().getString(R.string.error_please_add_bankcard), WalletToCosumeActivity.this, 1);
                    } else if (Cosume.equals("") || "0".equals(Cosume)) {
                        TipUtil.showToast(getResources().getString(R.string.error_please_input_cosume_amount), WalletToCosumeActivity.this, 1);
                    } else if (BankCardType.equals(getResources().getString(R.string.text_bankcard_type_2))) {
                        TipUtil.showToast(getResources().getString(R.string.error_nonsupport_credit_card), WalletToCosumeActivity.this, 1);
                    } else if (onCount(textFee, Cosume, Bamount)) {
                        TipUtil.showToast(getResources().getString(R.string.error_balance_not_enough), WalletToCosumeActivity.this, 1);
                    } else {
                        withdraw(Cosume, BankCard);

                    }
                    return true;
                }
                return false;
            }
        });
        payTypeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDatalist.size() > 0) {
                    initData();
                } else {
//                    TipUtil.showToast("您还未绑定银行卡", WalletRechareActivity.this, 1);
//                    showAppayRes();

//                    tvPayS.setText("添加银行卡");
                    edtCosume.setFocusable(false);
                    edtCosume.setEnabled(false);
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "2");
                    intent.putExtras(bundle);
                    intent.setClass(WalletToCosumeActivity.this, AddBankActivity.class);
                    startActivity(intent);

                }

            }
        });

        edtCosume.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edtCosume.setText(s);
                        edtCosume.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edtCosume.setText(s);
                    edtCosume.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edtCosume.setText(s.subSequence(0, 1));
                        edtCosume.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edtCosume.getText().toString().length() == 0) {
                    edFee.setText("");
                    TipUtil.showToast(getResources().getString(R.string.error_please_input_amount), WalletToCosumeActivity.this, 1);
                    layout_account_fee.setVisibility(View.GONE);
                } else {
//                    Log.e("mm",edtCosume.getText().toString());
                    layout_account_fee.setVisibility(View.VISIBLE);
                    getfee(edtCosume.getText().toString());
                }

            }
        });

    }

    /**
     * 获取绑定的银行卡
     */
    private void GetWithdrawCard() {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetWithdrawCard, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("获取绑定的银行卡接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject aData = res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        mDatalist.clear();
                        JSONArray bList = aData.getJSONArray("cardList");
                        if (bList.length() == 0) {
                            showAppayRes();
//                            TipUtil.showToast("您还未绑定银行卡", WalletToCosumeActivity.this, 1);
                        } else {
                            Bamount = aData.getString("balance");
                            for (int i = 0; i < bList.length(); i++) {
                                JSONObject item = (JSONObject) bList.get(i);
                                BankCard bankCard = new BankCard();
                                bankCard.setBankCardNo(item.getString("bankCardNo"));
                                bankCard.setPhone(item.getString("phone"));
                                bankCard.setAvailable(item.getString("available"));
                                bankCard.setLimit(item.getString("limit"));
//                                bankCard.setCardType(item.getString("cardType"));
//                                bankCard.setCardType("信用卡");
                                bankCard.setCardType(item.getString("accountType"));
//                                bankCard.setStatus(item.getString("status"));
                                bankCard.setCardName(item.getString("cardName"));
                                bankCard.setBankCode(item.getString("bankCode"));
                                mDatalist.add(i, bankCard);
                            }
                            Message msg = new Message();
                            msg.what = 1;
                            mHandler.sendMessage(msg);

                            if (mDatalist.get(0).getCardType().equals("02")) {
                                aBankName = mDatalist.get(0).getCardName();
                                aBankNumber = mDatalist.get(0).getBankCardNo();
                                aBankType = mDatalist.get(0).getBankCode();
                                BankCardType = mDatalist.get(0).getCardType();
                                BankCard = mDatalist.get(0).getBankCardNo();
                                String[] bankCodes = getResources().getStringArray(R.array.bankcode);
                                TypedArray ar = getResources().obtainTypedArray(R.array.bankicon);
                                for (int j = 0; j < bankCodes.length; j++) {

                                    if (bankCodes[j].toString().equals(mDatalist.get(0).getBankCode())) {
                                        imgBankLogo.setImageResource(ar.getResourceId(j, 0));
                                        break;
                                    }
                                }
                                tBankNanme.setText(getResources().getString(R.string.error_nonsupport_credit_card));

                            } else {
                                aBankName = mDatalist.get(0).getCardName();
                                aBankNumber = mDatalist.get(0).getBankCardNo();
                                aBankType = mDatalist.get(0).getBankCode();
                                BankCardType = mDatalist.get(0).getCardType();
                                BankCard = mDatalist.get(0).getBankCardNo();
                                tBankNanme.setText(aBankName);
//                tBankNumber_Type.setText("尾号" + aBankNumber.substring(aBankNumber.length() - 4, aBankNumber.length()) + " " + aBankType);

                                String[] bankCodes = getResources().getStringArray(R.array.bankcode);
                                TypedArray ar = getResources().obtainTypedArray(R.array.bankicon);
                                for (int j = 0; j < bankCodes.length; j++) {

                                    if (bankCodes[j].toString().equals(mDatalist.get(0).getBankCode())) {
                                        imgBankLogo.setImageResource(ar.getResourceId(j, 0));
                                        break;
                                    }
                                }
                            }

                        }


                    } else {//失败
                        TipUtil.showToast(message, WalletToCosumeActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletToCosumeActivity.this, 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), WalletToCosumeActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


    @Override
    protected void initData() {
        popupWindow = new ChoosePayPopupWindowS(WalletToCosumeActivity.this, mDatalist, "5");
        popupWindow.showAtLocation(findViewById(R.id.paymacth), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupWindow.setChoosePayWindowListItemClickListener(new ChoosePayPopupWindowS.PayChooseWindowListItemClickListener() {
            @Override
            public void onItemClick(BankCard message) {

                aBankName = message.getCardName();
                aBankNumber = message.getBankCardNo();
                aBankType = message.getBankCode();
                BankCardType = message.getCardType();
                tBankNanme.setText(aBankName);
                BankCard = message.getBankCardNo();
                String[] bankCodes = getResources().getStringArray(R.array.bankcode);
                TypedArray ar = getResources().obtainTypedArray(R.array.bankicon);
                for (int j = 0; j < bankCodes.length; j++) {

                    if (bankCodes[j].toString().equals(message.getBankCode())) {
                        imgBankLogo.setImageResource(ar.getResourceId(j, 0));
                        break;
                    }
                }

            }

            @Override
            public void onPayTypeClick(String Type) {

            }
        });

    }

    /**
     * 计算手续费
     */
    private void getfee(final String amount) {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetFee, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {


                    TipUtil.log("获取绑定的银行卡接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject aData = res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        textFee = aData.getString("fee");
                        edFee.setText(textFee);
                    } else {//失败
                        TipUtil.showToast(message, WalletToCosumeActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletToCosumeActivity.this, 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), WalletToCosumeActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("amount", amount.trim());
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    /**
     * 申请提现
     */
    private void withdraw(final String amount, final String BankCard) {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), WalletToCosumeActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Withdraw, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.showToast(getResources().getString(R.string.error_depositors_submit_success), WalletToCosumeActivity.this, 1);
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setClass(WalletToCosumeActivity.this, WalletActivity.class);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, WalletToCosumeActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletToCosumeActivity.this, 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), WalletToCosumeActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("amount", amount.trim());
//                Log.e("cardNo",BankCard);
                map.put("bankCardNo", BankCard);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    public void showAppayRes() {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(WalletToCosumeActivity.this);
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(getResources().getString(R.string.error_noting_binding_bankcard));
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("type", "2");
                intent.putExtras(bundle);
                intent.setClass(WalletToCosumeActivity.this, AddBankActivity.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    @Override
    public void onResume() {
        super.onResume();
        GetWithdrawCard();

    }

    public boolean onCount(String fee, String cosume, String bamount) {
        boolean isOK = true;
        double aFee = Double.parseDouble(fee);
        double aCosume = Double.parseDouble(cosume);
        double aBamount = Double.parseDouble(bamount);
        if (aFee + aCosume > aBamount) {
            return isOK;
        } else {
            isOK = false;
        }
        return isOK;
    }


}
